package org.shj.spring.boot.util;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.shj.spring.boot.base.OffsetLimitPageable;
import org.shj.spring.boot.base.param.Param;
import org.shj.spring.boot.base.param.QueryParam;
import org.shj.spring.boot.base.param.Sort;
import org.shj.spring.boot.base.param.SortEnum;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.List;

/**
 * Created by xuwei on 2017/9/7.
 */
public class JpaUtil {

    public static Pageable buildPageRequest(QueryParam queryEntity) {
        org.springframework.data.domain.Sort sort = buildSort(queryEntity.getSorts());
        if (queryEntity.getStartIndex() != null) {
            return new OffsetLimitPageable(queryEntity.getStartIndex(), queryEntity.getPageSize(), sort);
        } else {
            return new PageRequest(queryEntity.getPageNo(), queryEntity.getPageSize(), sort);
        }
    }

    private static org.springframework.data.domain.Sort buildSort(List<Sort> sorts) {
        if (CollectionUtils.isEmpty(sorts)) {
            return null;
        }
        List<org.springframework.data.domain.Sort.Order> orders = Lists.newArrayList();
        for (Sort sort : sorts) {
            orders.add(new org.springframework.data.domain.Sort.Order(
                    sort.getOrder() != null && sort.getOrder().equals(SortEnum.ASC) ?
                            org.springframework.data.domain.Sort.Direction.ASC :
                            org.springframework.data.domain.Sort.Direction.DESC, sort.getName()));
        }
        org.springframework.data.domain.Sort springSort = new org.springframework.data.domain.Sort(orders);
        return springSort;
    }

    public static <Q extends Param> boolean isPaging(Q queryEntity) {
        return queryEntity instanceof QueryParam && (((QueryParam) queryEntity).isPaging() || ((QueryParam) queryEntity).getStartIndex() != null);
    }
}
